<?php

namespace App\Http\Controllers\H5;

use App\Events\OrderEvent;
use App\Models\BlockItem;
use App\Models\ItemPush;
use App\Models\Order;

class IndexController extends BaseController
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        $treeCount = $this->user()->trees()->count();
        $energy = $this->user()->trees()->sum('energy');
        $wallet = $this->user()->wallet()->firstOrCreate([]);
        $items = ItemPush::with(['item'])->orderBy('displayorder')->limit(20)->get()->map(function ($item){
            if ($item->item) {
                if ($item->item->on_sale){
                    return $item->item;
                } else {
                    $item->delete();
                }
            } else {
                $item->delete();
            }
        });
        $foucsImgs = BlockItem::where('block_id', 1)->orderBy('displayorder')->get();
        return $this->view('h5.index', compact('items', 'wallet','treeCount', 'energy', 'foucsImgs'));
    }


    public function test()
    {
        return $this->view('h5.test');
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function checkLicense()
    {
        if ($this->user()->licensestatus)
        {
            return ajaxReturn();
        } else {
            return ajaxError(1, 'nodata', ['license'=>nl2br(setting('sysrulestxt'))]);
        }
    }

    public function acceptLicense()
    {
        $user = $this->user();
        $user->licensestatus = 1;
        $user->save();
        auth()->loginUsingId($user->uid);
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function getLicense()
    {
        return ajaxReturn(['license'=>nl2br(setting('sysrulestxt'))]);
    }
}
